import re
import json
from collections import defaultdict

def parse_log(log_content):
    results = {
        "groups": defaultdict(lambda: {"entries": defaultdict(dict)}),  # group_id → entry_id → data
        "simulation": {},
    }

    # 解析GPU组信息
    group_pattern = r'group: (\d+) gpu:0 gpuInterface finish ([\d.]+)% workCount:(\d+) tickCount:(\d+)'
    for idx, match in enumerate(re.finditer(group_pattern, log_content)):
        group_id = int(match.group(1))
        entry_id = idx
        results["groups"][group_id]["entries"][entry_id].update({
            "completion_percent": float(match.group(2)),
            "work_count": int(match.group(3)),
            "tick_count": int(match.group(4)),
        })

    occupancy_pattern = r'occ1:([\d.]+)%'
    occupancy_durations = [float(d) for d in re.findall(occupancy_pattern, log_content)]
    for idx, occupancy in enumerate(occupancy_durations):
        entry_id = idx
        for group_id in results["groups"]:
            if entry_id in results["groups"][group_id]["entries"]:
                results["groups"][group_id]["entries"][entry_id]["occupancy_percent"] = occupancy

    # 解析Ariel内存统计
    ariel_pattern = r'Page Table Sizes:\s+- Map entries\s+(\d+)\s+Page Table Coverages:\s+- Bytes\s+(\d+)'
    for idx, match in enumerate(re.findall(ariel_pattern, log_content)):
        entry_id = idx
        for group_id in results["groups"]:
            if entry_id in results["groups"][group_id]["entries"]:
                results["groups"][group_id]["entries"][entry_id].update({
                    "map_entries": int(match[0]),
                    "bytes": int(match[1])
                })
    
    # 解析 calculate_durations
    duration_pattern = r'Calculate duration: ([\d.]+)'
    calculate_durations = [float(d) for d in re.findall(duration_pattern, log_content)]
    for idx, duration in enumerate(calculate_durations):
        entry_id = idx
        for group_id in results["groups"]:
            if entry_id in results["groups"][group_id]["entries"]:
                results["groups"][group_id]["entries"][entry_id]["calculate_duration"] = duration

    # 解析模拟时间细节
    sim_time_match = re.search(r'Simulation is complete, simulated time: ([\d.]+) us', log_content)
    if sim_time_match:
        results["simulation"]["simulated_time_us"] = float(sim_time_match.group(1))


    # 转换 defaultdict 为普通列表
    final_groups = []
    for group_id, group_data in results["groups"].items():
        entries = []
        for entry_id, entry_data in group_data["entries"].items():
            entries.append(entry_data)
        final_groups.append({
            "group_id": group_id,
            "entries": entries
        })
    results["groups"] = final_groups

    return results

def process_log_file(input_path, output_path):
    with open(input_path, 'r') as f:
        content = f.read()
    
    parsed_data = parse_log(content)
    
    with open(output_path, 'w') as f:
        json.dump(parsed_data, f, indent=4)
    
    return parsed_data

# 使用示例
input_file = "../result/runtime2.log"
output_file = "../result/performance.json"
result = process_log_file(input_file, output_file)
print("Performance metrics extracted and saved to:", output_file)